<template>
  <div>
    <common-head :title="title"/>
    <div class="wrap2">
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="img in pics" :key="img.id">
        <img :src="img.pic" alt="">
      </van-swipe-item>
    </van-swipe>
    <h4>{{basicInfo.name}}</h4>
    <div class="content" v-html="content"></div>
    </div>
    <!-- 商品规格弹窗 -->
    <van-popup
      round
      closeable
      v-model="show"
      position="bottom"
      :style="{ height: '33%' }">
      <div>
        <van-card
          :num="sku.num"
          :price="sku.minPrice"
          :title="sku.name"
          :thumb="sku.pic"
        >
          <template #footer>
            <van-stepper v-model="sku.num" />
            <van-button @click="addCart" type="danger" size="large">确认</van-button>
          </template>
        </van-card>
      </div>
    </van-popup>
    <!-- /商品规格弹窗 -->
    <!-- 提交购物车 -->
    <van-goods-action>
      <van-goods-action-icon icon="home-o" text="首页" @click="$router.push('/home')" />
      <van-goods-action-icon icon="cart-o" :badge="$store.state.cart.items.length" text="购物车" @click="$router.push('/cart')" />
      <van-goods-action-button
        type="danger"
        text="加入购物车"
        @click="showSku"
      />
    </van-goods-action>
    <!-- /提交购物车 -->
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead'
import { fetchDetail, addCart } from 'api'
import { getToken } from 'utils'
import { Toast } from 'vant'
export default {
  name: 'detail',
  data () {
    return {
      title: '商品详情',
      basicInfo: {},
      pics: [],
      content: '',
      show: false,
      sku: {
        // 商品规格
        num: 1
      }
    }
  },
  created () {
    this.fetchDetail()
  },
  methods: {
    addCart () {
      addCart({
        goodsId: this.sku.id,
        number: 1,
        token: getToken()
      }).then(res => {
        if (res.data.code === 0) {
          this.$store.commit('cart/set_items', res.data.data.items)
        }
        Toast({
          type: 'success',
          message: '加入成功'
        })
      })
    },
    showSku () {
      // 弹出商品详情
      this.show = true
    },
    fetchDetail () {
      fetchDetail(this.$route.query.id).then(res => {
        // console.log(res)
        if (res.data.code === 0) {
          this.basicInfo = res.data.data.basicInfo
          this.pics = res.data.data.pics
          this.title = res.data.data.basicInfo.name
          this.sku = {
            ...this.sku,
            ...res.data.data.basicInfo
          }
          this.content = res.data.data.content.replace(/<img/gi, '<img style="display:block;width: 100%"')
        }
      })
    }
  },
  components: { CommonHead }
}
</script>

<style lang="scss" scoped>
.wrap2{
  padding-top: 46px;
  padding-bottom: 50px;
  img{
    width: 100%;
  }
}
</style>
